import React, { useEffect } from 'react';
// import { useTokenValidation } from '@/hooks/useLogin';
import { useAuth } from '@hooks/AuthContext';
import { CustomButton } from '@/components/CustomButton'
import { Dropdown, Avatar, Space } from 'antd';
import { CaretDownOutlined, SmileOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { Crisp } from "crisp-sdk-web";
import clsx from 'clsx';



export default function UserProfile({ className }) {
  const { isLoading, userInfo, logout } = useAuth();

  const navigate = useNavigate();
  const elogout = (e) => {
    e.preventDefault();
    logout();
    navigate('/login');
  }

  useEffect(() => {
    if (userInfo) {
      Crisp.configure('b3fd0179-cad4-4f34-b10a-186f3bb4300e', {
        autoload: false,
        tokenId: userInfo.phone_number,
        locale: 'zh-cn',
        session_merge: true
      });

      Crisp.user.setPhone(userInfo.phone_number);
      Crisp.user.setNickname(userInfo.name);
      userInfo.email && Crisp.user.setEmail(userInfo.email);
      Crisp.setPosition("left");
      Crisp.load();

    } else {
      Crisp.configure('b3fd0179-cad4-4f34-b10a-186f3bb4300e', {
        autoload: false,
        locale: 'zh-cn',
        session_merge: true
      });
      Crisp.setPosition("left");
      Crisp.load();
    }
  }, [userInfo]);

  const items = [
    {
      key: '1',
      label: (
        <a href="#" onClick={elogout}>
          退出登录
        </a>
      ),
    },
  ];

  if (isLoading) {
    return <div>Loading...</div>;
  }
  return (
    <nav className={className}>
      {userInfo ? (
        <div className="mt-8 lg:mt-0 flex items-center gap-4">
          <Avatar
            src={userInfo.profile} alt="User Avatar" />
          <Dropdown
            menu={{
              items,
            }}
          >
            <a onClick={(e) => e.preventDefault()}>
              {userInfo.name}
              <CaretDownOutlined />
            </a>
          </Dropdown>
        </div>
      ) : (
        <>
          <div className="mt-8 md:mt-0 flex flex-col lg:flex-row lg:items-center gap-6">
            <CustomButton href="/login" variant="outline">
              Log in
            </CustomButton>
            <CustomButton href="/register">
              Sign up
            </CustomButton>
          </div>
        </>
      )
      }

    </nav >
  );
}
